package com.sam.designpattern.proxy;

/**
 * @Author: Sam
 * @Date: 2022-08-03 09:55
 * @Description: 代理类
 */
public class Proxy implements UserModelApi {

    /**
     * 被代理对象
     */
    private UserModel realSubject = null;

    /**
     * 标识是否重载过数据
     */
    private boolean loaded = false;

    public Proxy(UserModel realSubject) {
        this.realSubject = realSubject;
    }

    @Override
    public String getUserId() {
        return realSubject.getUserId();
    }

    @Override
    public void setUserId(String userId) {
        realSubject.setUserId(userId);
    }

    @Override
    public String getDeptId() {
        if (!this.loaded) {
            //从数据库中重载对象
            reload();
            //设置重载标志为true
            this.loaded = true;
        }
        return realSubject.getDeptId();
    }

    @Override
    public void setDeptId(String deptId) {
        realSubject.setDeptId(deptId);
    }

    @Override
    public String getName() {
        return realSubject.getName();
    }

    @Override
    public void setName(String name) {
        realSubject.setName(name);
    }

    @Override
    public String getSex() {
        if (!this.loaded) {
            //从数据库中重载对象
            reload();
            //设置重载标志为true
            this.loaded = true;
        }
        return realSubject.getSex();
    }

    @Override
    public void setSex(String sex) {
        realSubject.setSex(sex);
    }

    /**
     * 重新查询数据库获取完整数据
     */
    public void reload() {
        //模拟请求数据库
        for (UserModel db : UserDB.USER_DB_LIST) {
            if (db.getUserId().equals(this.getUserId())) {
                this.realSubject = db;
                break;
            }
        }
    }
}
